<template>
  <div class="content-view">
    <!-- 工具栏 -->
    <div class="tool-bar">
      <div class="view">
        <el-input placeholder="按名称关键字筛选" v-model="searchKey.words" clearable>
          <template #suffix>
            <i class="iconfont icon-sousuo"></i>
          </template>
        </el-input>
        <!-- 条件搜索 -->
        <condition-query :data="data" @search="searchDone" />
      </div>
      <div class="view end">
        <!-- <el-button type="warning" @click="handleBatch" v-if="user.power*1 > 80">
          <i class="iconfont icon-jurassic_batch-work"></i>批量管理应用
        </el-button> -->
      </div>
    </div>
    <!-- 表格 -->
    <el-table 
      :data="clientList.filter(data => !searchKey.words || data.name.toLowerCase().includes(searchKey.words.toLowerCase()))"
      border stripe
      v-loading="loading" 
      :default-sort="{prop: 'dtCreate', order: 'ascending'}"
      @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center"/> -->
      <!-- <el-table-column prop="status" label="用户状态" sortable width="115" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status == 0?'success':'danger'">
            {{scope.row.status == 0?'正常':'停用'}}
          </el-tag> 
        </template>
      </el-table-column> -->
      <el-table-column prop="name" label="用户名称" sortable width="150" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="type" label="用户类型" sortable width="120"> </el-table-column>
      <!-- <el-table-column prop="upLevel" label="上级用户" sortable width="150" :show-overflow-tooltip="true"> </el-table-column> -->
      <el-table-column prop="contact" label="联系人" sortable width="100" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="phone" label="电话" sortable width="120" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="wholeAddress" label="地址" sortable :show-overflow-tooltip="true"> </el-table-column>   
      <el-table-column prop="dtCreate" label="创建时间" sortable width="180"> </el-table-column> 
      <el-table-column label="上架应用" fixed="right" width="220"> 
        <template #default="scope">
          已上架<el-tag type="primary" effect="dark" style="margin: 0 3px;">{{scope.row.appids.length}}</el-tag>个应用
          <el-button type="success" size="small" @click="handleBtn(scope.$index, scope.row, 'edit')" style="margin-left: 15px;">管理</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <page-div ref="PAGING_COM" @change="pageChange" />
    <!-- dialog -->
    <app-table ref="APP_TABLE" @done="appDone"/>
    <batch-app-dlg ref="BATCH_DLG" @done="appDone"/>
  </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import ConditionQuery from '../fun_mod/ConditionQuery.vue'
import PageDiv from '../fun_mod/PageDiv.vue'
import http from '@/axios/http'
import util from '@/assets/js/util'
import { ElNotification } from 'element-plus'
import AppTable from '../dialog/AppTable.vue'
import BatchAppDlg from '../dialog/BatchAppDlg.vue'
import mqtt from '@/assets/js/mqtt'
export default {
  components: { 
    ConditionQuery,
    PageDiv,
    AppTable,
    BatchAppDlg
  },
  props:['data'],
  setup() {
    const Global = getCurrentInstance().proxy
    let user = reactive({
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
    });

    onMounted(()=>{
      sessionStorage.removeItem('sBatchData')
      getClients()
      mqttOnMsg()
    })

    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        if (r.data.returnCode == 10000) {
          let d = r.data.data
          if (r.msgType == 61) {
          //console.log(d)
            let devFlag = sessionStorage.getItem('DEV_FLAG')
            if (devFlag == 'app_store') {
              for (let i in d) {
                let a = d[i].address
                if (!util.isNull(a)) {
                  d[i].wholeAddress = (a.province || '')+(a.city || '')+(a.district || '')+(a.addr || '')
                } else {
                  d[i].wholeAddress = ''
                }
                d[i].dtCreate = util.formatGmt(d[i].create_date)
                d[i].type = util.cilentType(d[i].scope)
              }
              clientList.value = d
              paging.total = r.data.count
              if (PAGING_COM.value) PAGING_COM.value.setData(paging)
            }
          }
        }  
      })
    }

    let clientList = ref([])
    let loading = ref(false)
    function getClients() {
      sessionStorage.setItem('DEV_FLAG','app_store')
      loading.value = true
      let msgCode = 61
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.name = searchKey.name
      m.contact = searchKey.contact
      m.phone = searchKey.phone
      m.province = searchKey.province
      m.city = searchKey.city
      if (searchKey.group) m.group = searchKey.group
      if (searchKey.qry_scope) m.qry_scope = searchKey.qry_scope
      if (user.power > 90) m.scope_length = 8
      // if (user.power > 80 && user.power < 90) m.scope_length = 12
      //if (searchKey.scope_length) m.scope_length = searchKey.scope_length
      m.status = 0
      m.indexPage = paging.index
      m.pageSize = paging.size
      g.message = m
    //console.log('用户查询：',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    // 多选
    let batchData = []
    function handleSelectionChange(e) {
      batchData = e
      sessionStorage.setItem('sBatchData',JSON.stringify(e))
    }

    // 分页
    let PAGING_COM = ref(null)
    let paging = reactive({
      total: 0,
      index: 1,
      size: 20
    })
    function pageChange(e) {
      paging.index = e
      getClients()
    }
    // 搜索
    let searchKey = reactive({
      words: '',
      name: '',
      contact: '',
      phone: '',
      province: '',
      city: '',
      group: '',
      qry_scope: '',
      scope_length: '',
      status: 0,
      dtStart: '',
      dtEnd: '',
    })
    function searchDone(e) {
      searchKey.words = ''
      searchKey.name = ''
      searchKey.contact = ''
      searchKey.phone = ''
      searchKey.province = ''
      searchKey.city = ''
      searchKey.group = ''
      searchKey.qry_scope = ''
      searchKey.scope_length = ''
      searchKey.dtStart = ''
      searchKey.status = ''
      searchKey.dtEnd = ''
      e.forEach(v=>{
        if (v.t == '用户名称') searchKey.name = v.v
        if (v.t == '联系人') searchKey.contact = v.v
        if (v.t == '电话') searchKey.phone = v.v
        if (v.t == 'province') searchKey.province = v.v
        if (v.t == 'city') searchKey.city = v.v
        if (v.t == '用户类型') searchKey.scope_length = v.v
        if (v.t == '状态') searchKey.status = v.v
        if (v.t == 'dtStart') searchKey.dtStart = v.v
        if (v.t == 'dtEnd') searchKey.dtEnd = v.v
      })
      paging.index = 1
      getClients()
    }

    // 编辑用户应用
    let APP_TABLE = ref(null)
    let clientInfo = ref({name: ''})
    function handleBtn(index,row,f) {
      APP_TABLE.value.open(row)
    }
    // 批量处理用户
    let BATCH_DLG = ref(null)
    function handleBatch() {
      let bd = JSON.parse(sessionStorage.getItem('sBatchData'))  || []
      if (batchData.length < bd.length) batchData = bd
      let e = {}
      e.flag = 'client'
      e.data = batchData
      BATCH_DLG.value.open(e)
    } 
    // 用户处理完成
    function appDone(e) {      
      setTimeout(()=>{
        getClients()
      },1)  
    }

    function isNull(v) {
      return util.isNull(v)
    }

    return{
      user, clientList, loading, handleSelectionChange, PAGING_COM, paging, pageChange, searchKey, searchDone,
      APP_TABLE,clientInfo, handleBtn, BATCH_DLG, handleBatch, appDone, 
      isNull
    }
  },
}
</script>

<style lang="scss" scoped src="./tab_content2.scss"></style>